
const ws = new WebSocket('ws://' + document.location.host + '/ws');
const chatContainer = document.getElementById('chat-container');
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-btn');

const newAiMessageElement = function() {
    const newMessage = document.createElement('div');
    newMessage.classList.add('message', 'ai-message');
    return newMessage;
}
const chatCtrl = {
    status: 'idle', // idle, waiting, receiving
    waitStartTime: null,
    aiMessageElement: null,
    aiMessage: "",
    reset: () => {
        chatCtrl.status = 'idle';
        chatCtrl.waitStartTime = null;
        chatCtrl.aiMessageElement = null;
        chatCtrl.aiMessage = "";
        sendButton.disabled = false;
    },
    wait: () => {
        sendButton.disabled = true;
        chatCtrl.status = 'waiting';
        chatCtrl.waitStartTime = Date.now();
        chatCtrl.aiMessageElement = newAiMessageElement();
        chatCtrl.aiMessage = "";
    }
};

ws.onmessage = function(event) {
    if (chatCtrl.status === 'waiting') {
        chatCtrl.status = 'receiving';
        chatContainer.appendChild(chatCtrl.aiMessageElement);
    }
    // check end
    if (chatCtrl.status === 'receiving' && event.data === '\0') {
        chatCtrl.reset();
        return;
    }
    chatCtrl.aiMessage += event.data;
    chatCtrl.aiMessageElement.innerHTML = `<pre>${chatCtrl.aiMessage}</pre>`;
    chatContainer.scrollTop = chatContainer.scrollHeight;
};

sendButton.onclick = function() {

    if (chatCtrl.status !== 'idle') {
        return;
    }
    chatCtrl.wait();

    const message = messageInput.value;
    if (message) {
        const newMessage = document.createElement('div');
        newMessage.textContent = message;
        newMessage.classList.add('message', 'user-message');
        chatContainer.appendChild(newMessage);

        ws.send(message);
        messageInput.value = '';
    }
};
messageInput.onkeydown = function(event) {
    if (event.keyCode === 13 && !event.shiftKey) {
        event.preventDefault();
        sendButton.click();
    }
}